<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>用户管理</title>
  <!--引入的vue.js-->
  <script src="/js/vue.js"></script>
  <!--引入elementUI的css-->
  <link  type="text/css" rel="stylesheet" href="/css/index.css">
  <!--引入elementUI的js-->
  <script src="/js/index.js"></script>
  <!--引入axios.js-->
  <script src="/js/axios.min.js"></script>
  <style>
    .app-container {
      padding: 20px;
      background-color: #f5f7fa;
      min-height: 100vh;
    }
    .search-container {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #ffffff;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
    .table-container {
      padding: 20px;
      background-color: #ffffff;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
    .action-buttons {
      display: flex;
      gap: 8px;
      justify-content: center;
    }
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
    .dialog-footer {
      text-align: right;
    }
    .avatar-cell {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .avatar-img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      object-fit: cover;
      cursor: pointer;
      border: 2px solid #409EFF;
      transition: all 0.3s ease;
    }
    .avatar-img:hover {
      transform: scale(1.1);
      box-shadow: 0 0 8px rgba(64, 158, 255, 0.6);
    }
    .status-normal {
      color: #67C23A;
      font-weight: bold;
    }
    .status-disabled {
      color: #F56C6C;
      font-weight: bold;
    }
    .gender-male {
      color: #409EFF;
    }
    .gender-female {
      color: #E65194;
    }
    .gender-unknown {
      color: #909399;
    }
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #8c939d;
    }
    .avatar-uploader-icon {
      font-size: 24px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }
    .avatar {
      width: 100px;
      height: 100px;
      display: block;
    }

    /* 更新后的完整样式 */
    .image-preview-container {
      position: relative;
      width: 100%;
      height: 50vh;
      overflow: hidden;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .image-preview-image {
      max-width: 100%;
      max-height: 50vh;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      cursor: grab;
      transition: transform 0.3s ease;
    }

    .image-controls-bottom {
      display: flex;
      justify-content: center;
      gap: 8px;
      margin-top: 16px;
      padding: 0 16px;
    }

    .image-control-btn {
      background-color: rgba(255, 255, 255, 0.9);
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 6px 12px;
      font-size: 12px;
      cursor: pointer;
      transition: all 0.3s ease;
    }

    .image-control-btn:hover {
      background-color: #f5f7fa;
      border-color: #a0a0a0;
    }

    .image-control-btn.active {
      background-color: #409eff;
      color: white;
      border-color: #409eff;
    }

    .image-control-btn:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  </style>
</head>
<body>
<div id="app" class="app-container">
  <!--搜索功能-->
  <div class="search-container">
    <el-row :gutter="15">
      <el-col :span="5">
        <el-input
                size="small"
                v-model="searchForm.realName"
                placeholder="请输入昵称"
                prefix-icon="el-icon-user-solid"
                clearable>
        </el-input>
      </el-col>
      <el-col :span="5">
        <el-input
                size="small"
                v-model="searchForm.userName"
                placeholder="请输入用户名"
                prefix-icon="el-icon-user"
                clearable>
        </el-input>
      </el-col>
      <el-col :span="5">
        <el-input
                size="small"
                v-model="searchForm.phonenumber"
                placeholder="请输入手机号"
                prefix-icon="el-icon-phone"
                clearable>
        </el-input>
      </el-col>
      <el-col :span="9">
        <el-button
                size="small"
                type="primary"
                icon="el-icon-search"
                @click="search">
          搜索
        </el-button>
        <el-button
                size="small"
                type="success"
                icon="el-icon-plus"
                @click="handleAdd">
          添加
        </el-button>
        <el-button
                size="small"
                type="warning"
                icon="el-icon-refresh"
                @click="refreshData">
          刷新
        </el-button>
      </el-col>
    </el-row>
  </div>

  <!--列表-->
  <div class="table-container">
    <el-table
            :data="tableData"
            style="width: 100%"
            border
            stripe
            highlight-current-row>
      <el-table-column label="用户头像" width="100" align="center">
        <template slot-scope="scope">
          <div class="avatar-cell">
            <img
                    :src="scope.row.filePath"
                    alt="头像"
                    class="avatar-img"
                    @click="previewAvatar(scope.row.filePath)">
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="realName" label="昵称" width="120" align="center"></el-table-column>
      <el-table-column prop="userName" label="用户名" width="150" align="center"></el-table-column>
      <el-table-column prop="phonenumber" label="手机号" width="120" align="center"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="200" align="center"></el-table-column>

      <!-- 性别列 -->
      <el-table-column label="性别" width="80" align="center">
        <template slot-scope="scope">
          <span :class="{
            'gender-male': scope.row.sex === '0',
            'gender-female': scope.row.sex === '1',
            'gender-unknown': scope.row.sex === '2'
          }">
            {{ sexMap[scope.row.sex] }}
          </span>
        </template>
      </el-table-column>

      <!-- 状态列 -->
      <el-table-column label="用户状态" width="100" align="center">
        <template slot-scope="scope">
          <span :class="{
            'status-normal': scope.row.status === '0',
            'status-disabled': scope.row.status === '1'
          }">
            {{ statusMap[scope.row.status] }}
          </span>
        </template>
      </el-table-column>

      <!-- 备注 -->
      <el-table-column prop="remark" label="备注" min-width="180" align="center">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.remark" placement="top" v-if="scope.row.remark">
            <span class="remark-text">{{ scope.row.remark }}</span>
          </el-tooltip>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="280" align="center" fixed="right">
        <template slot-scope="scope">
          <div class="action-buttons">
            <el-button
                    size="mini"
                    type="success"
                    @click="handleAssignRole(scope.row.userId)"
                    icon="el-icon-setting">
              授予角色
            </el-button>
            <el-button
                    size="mini"
                    type="primary"
                    @click="handleEdit(scope.$index, scope.row)"
                    icon="el-icon-edit">
              编辑
            </el-button>
            <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                    icon="el-icon-delete">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!--分页功能-->
    <div class="pagination-container">
      <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[5,10,15,20,100]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              background>
      </el-pagination>
    </div>
  </div>

  <!-- 添加/更新对话框 -->
  <el-dialog
          :title="title"
          :visible.sync="dialogFormVisible"
          width="500px"
          :close-on-click-modal="false">
    <el-form
            :model="form"
            :rules="rules"
            ref="form"
            label-width="100px"
            style="padding-right: 20px;">

      <el-form-item label="用户头像" prop="filePath">
        <el-upload
                class="avatar-uploader"
                action="/user/uploadPic"
                name="pic"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="用户名" prop="userName">
        <el-input
                v-model="form.userName"
                autocomplete="off"
                placeholder="请输入用户名">
        </el-input>
      </el-form-item>


      <!-- 密码字段：仅在编辑时显示 -->
      <el-form-item
              label="用户密码"
              prop="password"
              v-if="title === '用户更新'">
        <el-input
                v-model="form.password"
                type="password"
                autocomplete="off"
                placeholder="请输入新密码（留空则不修改）">
        </el-input>
      </el-form-item>

      <el-form-item label="昵称" prop="realName">
        <el-input
                v-model="form.realName"
                autocomplete="off"
                placeholder="请输入昵称">
        </el-input>
      </el-form-item>

      <el-form-item label="手机号" prop="phonenumber">
        <el-input
                v-model="form.phonenumber"
                autocomplete="off"
                placeholder="请输入手机号">
        </el-input>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input
                v-model="form.email"
                autocomplete="off"
                placeholder="请输入邮箱">
        </el-input>
      </el-form-item>

      <el-form-item label="性别" prop="sex">
        <el-select
                v-model="form.sex"
                placeholder="请选择性别"
                style="width: 100%;">
          <el-option label="男" value="0"></el-option>
          <el-option label="女" value="1"></el-option>
          <el-option label="未知" value="2"></el-option>
        </el-select>
      </el-form-item>

      <!-- 状态字段：仅在编辑时显示 -->
      <el-form-item
              label="用户状态"
              prop="status"
              v-if="title === '用户更新'">
        <el-select
                v-model="form.status"
                placeholder="请选择状态"
                style="width: 100%;">
          <el-option label="正常" value="0"></el-option>
          <el-option label="停用" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
                type="textarea"
                v-model="form.remark"
                autocomplete="off"
                placeholder="请输入备注"
                :rows="3">
        </el-input>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button @click="resetForm('form')">重置</el-button>
      <el-button type="primary" @click="submitForm('form')">确 定</el-button>
    </div>
  </el-dialog>

  <!-- 头像预览弹窗 -->
  <el-dialog
          :visible.sync="dialogVisible"
          title="用户头像预览"
          width="50%"
          center>
    <div class="image-preview-container">
      <!-- 图片显示区域 -->
      <img
              :src="dialogImageUrl"
              alt="预览"
              class="image-preview-image"
              :style="{ transform: `scale(${scale})` }"
              @wheel.prevent="handleWheel">
    </div>

    <!-- 控制按钮 - 放在图片下方 -->
    <div class="image-controls-bottom">
      <button
              class="image-control-btn"
              @click="zoomIn"
              :disabled="scale >= 3">
        放大 (+)
      </button>
      <button
              class="image-control-btn"
              @click="zoomOut"
              :disabled="scale <= 0.5">
        缩小 (-)
      </button>
      <button
              class="image-control-btn"
              @click="resetZoom">
        重置 (1x)
      </button>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">关闭</el-button>
    </div>
  </el-dialog>

  <!-- 角色授权弹窗 -->
  <el-dialog
          :title="dialogTitle"
          :visible.sync="roleDialogVisible"
          width="500px"
          :close-on-click-modal="false">
    <el-form :model="roleForm" label-width="80px">
      <el-form-item label="角色">
        <el-checkbox-group v-model="selectedRoleIds">
          <el-checkbox
                  v-for="role in allRoles"
                  :key="role.roleId"
                  :label="role.roleId"
                  :disabled="role.disabled">
            {{ role.roleName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="roleDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitRoleAssign">确 定</el-button>
    </div>
  </el-dialog>

</div>
<script>
  new Vue({
    el:'#app',
    data() {
      return {
        tableData: [],
        currentPage: 1, //分页参数  页码，第几页
        pageSize: 10, //分页参数  每页显示数量
        total: 100,//分页参数  总数量
        searchForm: {}, //搜索的form对象
        dialogFormVisible: false,//是否显示当前对话框  false 不显示
        title: '用户添加', //弹出对话框的标题信息
        form: {  //提交数据的form对象
          userName: '',
          realName: '',
          password: '', // 新增密码字段
          phonenumber: '',
          email: '',
          sex: '',
          status: '',
          remark: ''
        },
        // 表格中显示性别和状态，中文
        sexMap: {
          '0': '男',
          '1': '女',
          '2': '未知'
        },
        statusMap: {
          '0': '正常',
          '1': '停用'
        },
        // 新增：头像上传相关
        imageUrl: '',
        // 新增：头像预览相关
        dialogImageUrl: '',     // 当前预览图片地址
        dialogVisible: false,   // 是否显示弹窗
        scale: 1,               // 图片缩放比例
        offsetX: 0,             // 水平偏移量
        offsetY: 0,             // 垂直偏移量

        // 角色授权相关
        roleDialogVisible: false,
        dialogTitle: '授予角色',
        allRoles: [],           // 所有角色列表
        selectedRoleIds: [],    // 已选中的角色ID
        currentUserId: null,    // 当前操作的用户ID
        roleForm: {},

        // ... 其他属性
        originalForm: {},// 用于保存用户更新重置前的原始数据
        formLabelWidth: '120px', //label的宽度 部门名称   部门位置
        rules: {
          userName: [
            {required: true, message: '请输入账号名', trigger: 'blur'},
            {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
          ],
          realName: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
          ],
          phonenumber: [
            {required: true, message: '请输入手机号', trigger: 'blur'},
            {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
          ],
          email: [
            {required: false, message: '请输入邮箱地址', trigger: 'blur'},
            {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
          ],
          sex: [
            {required: true, message: '请选择性别', trigger: 'change'}
          ],
          status: [
            {required: true, message: '请选择用户状态', trigger: 'change'}
          ]
        }
      }
    },
    created(){//页面初始化时要执行的代码
      //调用方法
      this.loadData();
    },
    methods: {//当前页面中元素事件触发方法，函数，都写在这。。。
      //封装数据加载方法
      loadData(){
        //定义 this是vue对象
        let _this = this;
        // 向给定ID的用户发起请求  {"deptNo":101,"deptName":"下","loc":"由"}
        //          searchForm: {"deptNo":'',"deptName":'',"loc":''}
        axios.post('/user/queryByPage',{"pageNo":this.currentPage,"pageSize": this.pageSize,"data": this.searchForm})
                .then(function (response) {
                  // 处理成功情况   response后台给我们响应的数据
                  console.log(response);
                  //判断返回状态
                  if(response.data.code==200){
                    //如果在这里面直接使用this，就是当前axios对象
                    _this.tableData = response.data.data.list;
                    _this.total=response.data.data.total;
                  }
                })
                .catch(function (error) {
                  // 处理错误情况
                  console.log(error);
                })
                .finally(function () {
                  // 总是会执行
                });
      },

      //每页数量发生变化
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        //当前页赋值
        this.pageSize = val;
        //调用方法
        this.loadData();
      },

      //页码 第几页  发生变化
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        //当前页赋值
        this.currentPage = val;
        //调用方法
        this.loadData();
      },

      //搜索功能
      search(){
        //调用方法
        this.loadData();
      },

      // 刷新数据
      refreshData() {
        // 清空搜索条件
        this.searchForm = {};
        // 调用加载方法
        this.loadData();
      },

      //提交表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // alert('submit!');
            //校验成功
            //触发提交  提交的处理业务
            //alert('submit!');

            //定义提交url地址
            let uri = '/user/add';
            //let uri = '';
            //判断是否是更新
            if(this.title == '用户更新'){
              uri='/user/edit';
              // 如果密码为空，则不发送密码字段
              if (!this.form.password || this.form.password.trim() === '') {
                delete this.form.password; // 移除密码字段
              }
            }
            // if(this.title == '部门更新'){
            //     uri='/dept/edit';
            // }else{
            //     uri = '/dept/add';
            // }

            //定义 this是vue对象
            let _this = this;
            //this.form={"deptName":xxx,"loc":xxx}
            axios.post(uri,this.form)
                    .then(function (response) {
                      // 处理成功情况   response后台给我们响应的数据

                      console.log(response);
                      //判断返回状态
                      if(response.data.code==200){
                        //提示成功
                        _this.$message({
                          message: '操作成功',
                          type: 'success'
                        });
                        //调用查询
                        _this.loadData();
                        //关闭对话框
                        _this.dialogFormVisible=false;
                      }else{
                        _this.$message.error('操作失败');
                      }
                    })
                    .catch(function (error) {
                      // 处理错误情况
                      console.log(error);
                    })
                    .finally(function () {
                      // 总是会执行
                    });
          } else {//校验失败
            console.log('error submit!!');
            return false;
          }
        });
      },

      //重置表单
      resetForm(formName) {
        // 如果是更新操作，恢复到原始数据；否则清空表单
        if (this.title === "用户更新") {
          // 恢复到编辑前的原始数据
          this.form = JSON.parse(JSON.stringify(this.originalForm));
          // 清除密码字段，避免显示原密码
          this.form.password = '';
          // 同时恢复图片预览
          this.imageUrl = this.originalForm.filePath ? this.originalForm.filePath : '';
          // 重新验证表单
          this.$nextTick(() => {
            // 清除验证，formName：表单ref
            this.$refs[formName].clearValidate();
          });
        } else {
          // 添加操作时，清空表单
          this.form={
            userName: '',
            password: '', // 新增密码字段
            realName: '',
            phonenumber: '',
            email: '',
            sex: '', // 确保sex字段有默认值
            status: '', // 确保status字段有默认值
            remark: ''
          };
          // 添加操作时，清空表单及验证
          this.$refs[formName].resetFields();
          // 同时清除图片预览
          this.imageUrl = '';
        }
      },

      //处理添加，弹出添加对话框
      handleAdd(){
        //弹框出现
        this.dialogFormVisible = true;
        //执行重置，清空原来的数据
        // if(this.form.deptName!=null&&this.form.deptName!=''){
        //     this.$refs['form'].resetFields();
        // }
        //改变title
        this.title="用户添加";
        //把form重复赋值为{}
        this.form={
          userName: '',
          realName: '',
          phonenumber: '',
          email: '',
          sex: '', // 确保sex字段有默认值
          status: '', // 确保status字段有默认值
          remark: ''
        };
        // 同时清除图片预览
        this.imageUrl = '';
        //调用重置方法
        this.resetForm('form');
      },

      //处理更新
      handleEdit(index, row) {
        // console.log(index);
        // console.log(row);
        // console.log(index, row);
        // console.log(row.deptNo)
        // console.log(row.deptName)
        // console.log(row.loc)
        //弹框出现
        this.dialogFormVisible = true;
        //改变title
        this.title="用户更新";
        //给当前form赋值  js浅克隆和深克隆
        //js深克隆  双向数据绑定     深克隆: row是json对象  需要先把json对象转为json字符串stringify  再把json字符串转回为对象parse

        //保存原始数据的副本
        this.originalForm = JSON.parse(JSON.stringify(row));
        this.form = JSON.parse(JSON.stringify(row));

        // 清除验证状态
        this.resetForm('form');
        //在控制台打印出表单中的三个字段值，用于验证数据是否正确赋值
        // console.log(this.form.deptNo)
        // console.log(this.form.deptName)
        // console.log(this.form.loc)
      },

      //处理删除,DeptController中public Result deleteById({@RequestBody，不能加}Integer deptNo)，中不能加@RequestBody
      handleDelete(index, row) {
        // console.log(index);
        // console.log(row);
        // console.log(index, row);
        // console.log(row.deptNo)
        // console.log(row.deptName)
        // console.log(row.loc)
        this.$confirm('此操作将永久删除该数据吗, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //使用axios删除
          //定义 this是vue对象
          let _this = this;
          //this.form={"deptName":xxx,"loc":xxx}
          axios.delete('/user/deleteById?userId=' + row.userId)
                  .then(function (response) {
                    // 处理成功情况   response后台给我们响应的数据
                    console.log(response);
                    //判断返回状态
                    if(response.data.code==200){
                      //提示成功
                      _this.$message({
                        message: '删除成功',
                        type: 'success'
                      });
                      //调用查询
                      _this.loadData();
                    }else{
                      _this.$message.error(response.data.message || '删除失败');
                    }
                  })
                  .catch(function (error) {
                    // 处理错误情况
                    console.log(error);
                  })
                  .finally(function () {
                    // 总是会执行
                  });
        }).catch(() => {
          this.$message({

            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //上传图片成功
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        alert(JSON.stringify(file));
        this.form.filePath = file.response.data.filePath;
        this.form.fileName = file.response.data.originName;
      },

      //上传图片之前
      beforeAvatarUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        const isLt5M = file.size / 1024 / 1024 < 5;

        // if (!isJPG) {
        //   this.$message.error('上传头像图片只能是 JPG 格式!');
        // }
        if (!isLt5M) {
          this.$message.error('上传头像图片大小不能超过 5MB!');
        }
        // return isJPG && isLt2M;
        return isLt5M;
      },

      // 预览头像
      previewAvatar(url) {
        this.dialogImageUrl = url;
        this.dialogVisible = true;
        this.scale = 1; // 重置缩放比例
        this.offsetX = 0;
        this.offsetY = 0;
      },

      // 放大图片
      zoomIn() {
        if (this.scale < 3) {
          this.scale += 0.2;
        }
      },

      // 缩小图片
      zoomOut() {
        if (this.scale > 0.5) {
          this.scale -= 0.2;
        }
      },

      // 重置缩放
      resetZoom() {
        this.scale = 1;
        this.offsetX = 0;
        this.offsetY = 0;
      },

      // 鼠标滚轮缩放
      handleWheel(event) {
        const delta = event.deltaY > 0 ? -0.1 : 0.1;
        const newScale = this.scale + delta;

        if (newScale >= 0.5 && newScale <= 3) {
          this.scale = newScale;
        }
      },

      // 关闭弹窗
      handleCancel() {
        this.dialogVisible = false;
        this.scale = 1;
        this.offsetX = 0;
        this.offsetY = 0;
      },

      // 点击"授予角色"
      handleAssignRole(userId) {
        this.currentUserId = userId;
        this.selectedRoleIds = [];
        this.loadAllRoles(); // 加载所有角色
        this.loadUserRoles(userId); // 加载当前用户已有角色
        this.roleDialogVisible = true;
      },

      // 加载所有角色
      loadAllRoles() {
        let _this = this;
        axios.get('/user/roles/all') // 需要新增接口
                // .then(res => {
                //     this.allRoles = res.data;
                // });
                .then(function(response) {
                  if (response.data.code === 200) {
                    _this.allRoles = response.data.data;
                  }
                })
                .catch(function(error) {
                  console.log(error);
                });
      },

      // 加载当前用户已有角色
      loadUserRoles(userId) {
        let _this = this;
        axios.get(`/user/roles/${userId}`)
                .then(function(response) {
                  if (response.data.code === 200) {
                    const userRoles = response.data.data;
                    if (userRoles && userRoles.length > 0) {
                      _this.selectedRoleIds = userRoles.map(role => role.roleId);
                    }
                  }
                })
                .catch(err => {
                  console.error('加载用户角色失败:', err);
                  this.$message.error('获取角色失败');
                });
      },

      // 提交角色分配
      submitRoleAssign() {
        let _this = this;
        axios.post('/user/assignRoles', {
          userId: this.currentUserId,
          roleIds: this.selectedRoleIds
        })
                .then(function(response) {
                  if (response.data.code === 200) {
                    _this.$message.success('角色分配成功');
                    _this.roleDialogVisible = false;
                    // 刷新用户列表
                    _this.loadData();
                  } else {
                    _this.$message.error('角色分配失败');
                  }
                })
                .catch(function(error) {
                  console.log(error);
                  _this.$message.error('网络错误');
                });
      }

    }
  })
</script>
</body>
</html>
